<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2014 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace plugins\crawler\controller; //Demo插件英文名，改成你的插件英文就行了

use cmf\controller\PluginAdminBaseController;
use think\Db;

use plugins\crawler\model\CrawlerRuleModel;
use plugins\crawler\model\CrawlerSiteModel;
use plugins\crawler\model\DictionaryModel;
use app\portal\model\PortalCategoryModel;


class AdminRuleController extends PluginAdminBaseController
{

    protected function _initialize()
    {
        parent::_initialize();
        $adminId = cmf_get_current_admin_id();//获取后台管理员id，可判断是否登录
        if (!empty($adminId)) {
            $this->assign("admin_id", $adminId);
        }
    }

    /**
     * 采集插件规则
     * @adminMenu(
     *     'name'   => '采集规则',
     *     'parent' => 'admin/Plugin/default',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '采集规则',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $crawlerSiteId      = $this->request->param('crawler_site_id', 0, 'intval');
        $crawlerRuleModel = new CrawlerRuleModel();
        $crawlerSiteModel = new CrawlerSiteModel();

        $site = $crawlerSiteModel->find($crawlerSiteId);

        //category
        $rules = $crawlerRuleModel
            ->where(['crawler_site_id' => $crawlerSiteId])
            ->paginate();
        
        // 获取分页显示
        $page = $rules->render();

        //var_dump($rules[0]->category);die;

        //$sites = Db::name("crawler_site")->all();
        //$demos = PluginDemoModel::all();

        // print_r($demos);

        $this->assign("siteid", $crawlerSiteId);
        $this->assign("site", $site);
        $this->assign("rules", $rules);
        $this->assign("page", $page);

        return $this->fetch('/admin_rule');
    }

    /**
     * 添加采集规则
     * @adminMenu(
     *     'name'   => '添加规则',
     *     'parent' => 'admin/Plugin/default',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加规则',
     *     'param'  => ''
     * )
     */
    public function add()
    {
        $crawlerSiteId      = $this->request->param('crawler_site_id', 0, 'intval');

        $crawlerRule = new CrawlerRuleModel();
        $portalCategory = new PortalCategoryModel();
        $dictionary = new DictionaryModel();
        $crawlerSiteModel = new CrawlerSiteModel();

        $site = $crawlerSiteModel->find($crawlerSiteId);

        $categories = $portalCategory->where(['status' => '1'])->select();
        $dictionaries = $dictionary->where(['status' => '1', 'type' => '1'])->select();

        $this->assign("siteid", $crawlerSiteId);
        $this->assign("site", $site);
        $this->assign("categories", $categories);
        $this->assign("dictionaries", $dictionaries);

        return $this->fetch('/admin_rule_add');
    }

    /**
     * 保存修改插件规则
     * @adminMenu(
     *     'name'   => '保存编辑规则',
     *     'parent' => 'admin/Plugin/default',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '保存编辑规则',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        if ($this->request->isPost()) {
            
            $result = $this->validate($this->request->param(), 'CrawlerRule');
            
            $data['rulename']        = $this->request->param('rulename');
            $data['listpath']        = htmlspecialchars_decode($this->request->param('listpath'));
            $data['pagepath']        = $this->request->param('pagepath');
            $data['category_id']     = $this->request->param('category_id');
            $data['dictionary_id']   = $this->request->param('dictionary_id');
            $data['crawler_site_id'] = $this->request->param('crawler_site_id');

            $crawlerSiteModel = new CrawlerSiteModel();

            $site = $crawlerSiteModel->find($data['crawler_site_id']);

            $data['baseuri']         = $site->siteurl;
            $data['create_time']     = time();
            if ($result !== true) {
                // 验证失败 输出错误信息
                $this->error($result);
            } else {
                $result = DB::name('crawler_rule')->insert($data);
                if ($result !== false) {
                    $this->success("保存成功！");
                } else {
                    $this->error("保存失败！");
                }
            }
        }
    }


    /**
     * 编辑插件规则
     * @adminMenu(
     *     'name'   => '编辑规则',
     *     'parent' => 'admin/Plugin/default',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑规则',
     *     'param'  => ''
     * )
     */
    public function edit()
    {
        $id      = $this->request->param('id', 0, 'intval');
        $crawlerRule = new CrawlerRuleModel();
        $portalCategory = new PortalCategoryModel();
        $dictionary = new DictionaryModel();
        $crawlerSiteModel = new CrawlerSiteModel();

        $rule = $crawlerRule->find($id);

        $site = $crawlerSiteModel->find($rule->crawler_site_id);
        
        $categories = $portalCategory->where(['status' => '1'])->select();
        $dictionaries = $dictionary->where(['status' => '1', 'type' => '1'])->select();

        $this->assign("rule", $rule);
        $this->assign("site", $site);
        $this->assign("siteid", $site->id);
        $this->assign("categories", $categories);
        $this->assign("dictionaries", $dictionaries);

        return $this->fetch('/admin_rule_edit');
    }


    /**
     * 保存修改插件规则
     * @adminMenu(
     *     'name'   => '保存编辑规则',
     *     'parent' => 'admin/Plugin/default',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '保存编辑规则',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        if ($this->request->isPost()) {
            
            $result = $this->validate($this->request->param(), 'CrawlerRule');
            
            $id = $this->request->param('id', 0, 'intval');

            $data['rulename']        = $this->request->param('rulename');
            $data['listpath']        = htmlspecialchars_decode($this->request->param('listpath'));
            $data['pagepath']        = $this->request->param('pagepath');
            $data['category_id']     = $this->request->param('category_id');
            $data['dictionary_id']   = $this->request->param('dictionary_id');            
            $data['crawler_site_id'] = $this->request->param('crawler_site_id');

            if ($result !== true) {
                // 验证失败 输出错误信息
                $this->error($result);
            } else {
                $result = DB::name('crawler_rule')->where(['id' => $id])->update($data);
                if ($result !== false) {
                    $this->success("保存成功！");
                } else {
                    $this->error("保存失败！");
                }
            }
        }
    }


    /**
     * 删除采集规则
     * @adminMenu(
     *     'name'   => '删除采集规则',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '删除采集规则 如规则下面有列表则无法删除',
     *     'param'  => ''
     * )
     */
     public function delete()
     {
         $id = $this->request->param("id", 0, 'intval');
 
         if (empty($id)) {
             $this->error(lang("NO_ID"));
         }
         $crawlerRuleModel = new CrawlerRuleModel();
 
         $urlCount = Db::name('crawler_url')->where('crawler_rule_id', $id)->count();
         
         if($urlCount) {
             $this->error(lang("请先删除采集列表"));
         }
         else
         {
             $crawlerRuleModel->where(['id' => $id])->delete();
             $this->success(lang("DELETE_SUCCESS"));
         }
     }
 
    

}
